<template>
  <div class="wh-gaode-wraper">
    <div class="wh-gaode" id="wh-map-component-geode"></div>
    <div class="wh-gaode-infoWindow" ref="wh-gaode-infoWindow">
      <div class="wh-gaode-infoWindow-title">
        <p>
          {{currentInfo.title || '提示'}}
        </p>
        <img @click="onCloseInfoWindow" src="../assets/close.png" alt="">
      </div>
      <div class="wh-gaode-infoWindow-content">
        {{currentInfo.content || '内容'}}
      </div>
      <div class="wh-gaode-infoWindow-bottom"></div>
    </div>
    <div class="wh-geode-path-infoWindow" ref="wh-geode-path-infoWindow"></div>
  </div>
</template>

<script>
// import AMapLoader from '../common/gaodeLoader.js'
import loadScript from '../common/loadScript.js'
// import AMapLoader from "@amap/amap-jsapi-loader"
export default {
  data() {
    return {
      AMap: null,
      map: null,
      pointsList: [],
      passedList: [],
      pathList: [],
      pathConfig: {},
      navgList: [],
      infoWindow: null,
      currentInfo: {}

    }
  },
  props: {
    loadedMap: {
      type: Function,
      default: null
    },
  },
  methods: {
    loadMap(options) {
      console.log('创建高德地图');
      return new Promise((resolve, reject) => {
        if(!options.loadConfig) {
          console.error('未配置地图加载所需的必要配置');
          reject('未配置地图加载所需的必要配置')
        }
        const securityConfig = {}
        if (options.loadConfig.securityHost) {
          // 高德地图的api请求地址
          securityConfig.serviceHost = options.loadConfig.securityHost // 地址
        } else if (options.loadConfig.securityJsCode) {
          // 高德地图key的密钥
          securityConfig.securityJsCode = options.loadConfig.securityJsCode// 密钥
        } else {
          console.warn('未配置高德key的密钥或者服务地址')
        }
        window._AMapSecurityConfig = securityConfig
        if (!options.loadConfig.key) {
          console.warn('未配置高德key')
          reject('未配置高德key')
        }
        // else {
        //   config = {
        //     key: options.loadConfig.key,
        //     version: options.loadConfig.version,
        //     AMapUI: options.loadConfig.AMapUI,
        //     Loca: options.loadConfig.Loca
        //   }
        // }
        const apiHost = 'https://webapi.amap.com/maps'
        const version = options.loadConfig.version || '2.0'
        const key = options.loadConfig.key
        const url = options.loadConfig.customUrl?options.loadConfig.customUrl:`${apiHost}?v=${version}&key=${key}`
        loadScript('AMap', url).then(() => {
          this.AMap = AMap
          const gaodeMapLayer = new AMap.TileLayer({
            getTileUrl: options.loadConfig.tileUrl,
            opacity: 1,
            zIndex: 9
          })
          const mapConfig = options.mapConfig?options.mapConfig:{}
          mapConfig.zooms = [mapConfig.minZoom || 2, mapConfig.maxZoom || 20]
          this.map = new AMap.Map('wh-map-component-geode', {
            layers: options.loadConfig.tileUrl?[gaodeMapLayer]:null,
            ...options.mapConfig
          })
          if (options.mapConfig.bounds && options.mapConfig.bounds.length === 2) {
            const bounds = new AMap.Bounds(options.mapConfig.bounds[0], options.mapConfig.bounds[1]);
            this.map.setLimitBounds(bounds);
          }
          this.map.on('click', this.onClickMap)
          this.initInfoWindow()
          this.loadedMap(this.map)
          resolve(this.map)
        }).catch(err => {
          console.log(err);
        })
        // AMapLoader.load({
        //   ...config
        // }).then((AMap) => {
        //   // 标准normal
        //   // 幻影黑dark
        //   // 月光银light
        //   // 远山黛whitesmoke
        //   // 草色青fresh
        //   // 雅士灰grey
        //   // 涂鸦graffiti
        //   // 马卡龙macaron
        //   // 靛青蓝blue
        //   // 极夜蓝darkblue
        //   // 酱籽wine
        //   this.AMap = AMap
        //   const gaodeMapLayer = new AMap.TileLayer({
        //     getTileUrl: options.loadConfig.tileUrl,
        //     opacity: 1,
        //     zIndex: 9
        //   })
        //   // : new AMap.createDefaultLayer({
        //   //   // zooms: [3,20],    // 可见级别
        //   //   visible: true,    // 是否可见
        //   //   opacity: 1,       // 透明度
        //   //   zIndex: 0         // 叠加层级
        //   // })
        //   this.map = new AMap.Map('wh-map-component-geode', {
        //     layers: options.loadConfig.tileUrl?[gaodeMapLayer]:null,
        //     ...options.mapConfig
        //   })
        //   this.map.on('click', this.onClickMap)
        //   resolve(this.map)
        // }).catch(e => {
        //   reject(e)
        // })
      })
    },
    initInfoWindow () {
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true,  //使用自定义窗体
        content: this.$refs['wh-gaode-infoWindow'],
        offset: new AMap.Pixel(0, -45),
        closeWhenClickMap: true
      });
      // this.infoWindow = new AMap.InfoWindow({
      //    content: '信息窗体',
      //    anchor: 'bottom-center',
      // });
    },
    loadMarker (markerList) {

      console.log('加载 marker');
      var markers = []
      for (var i = 0; i < markerList.length; i++) {

        var markerOptions = markerList[i].options?markerList[i].options:{}
        var size = [markerOptions.width || 28, markerOptions.height || 28]
        var offfset = new AMap.Pixel(-size[0]/2, -size[1])
        var icon = new AMap.Icon({
          image: markerOptions.icon || require('../assets/marker/marker-6.png'),
          size: new AMap.Size(size[0], size[1]),
          imageSize: new AMap.Size(size[0], size[1]),
          imageOffset: new AMap.Pixel(0, 0)
        })
        markerOptions.icon = icon
        markerOptions.zIndex = markerOptions.zIndex || 12
        markerOptions.opacity = markerOptions.opacity || 1
        markerOptions.offset = offfset
        for (var j = 0; j < markerList[i].list.length; j++) {

          var marker = new AMap.Marker({
            position: markerList[i].list[j].position,
            extData: {
              showInfoWindow: markerOptions.showInfoWindow,
              customInfoWindow: markerOptions.customInfoWindow,
              ...markerList[i].list[j].properties
            },
            ...markerOptions
          });
          marker.on('click', this.onClickMarker)
          markers.push(marker)
        }
      }
      this.markerLayer = new AMap.OverlayGroup(markers)
      this.map.add(this.markerLayer)
    },
    loadPolygon (polygonList) {
      console.log('加载多边形');
      var polygons = []
      // cursor: polygonList[i].polygonOptions.cursor || 'cursor',
      // strokeColor: polygonList[i].polygonOptions.strokeColor || '#00D3FC',
      // strokeOpacity: polygonList[i].polygonOptions.strokeOpacity || 0.9,
      // strokeWeight: polygonList[i].polygonOptions.strokeWeight || 2,
      // fillColor: polygonList[i].polygonOptions.fillColor || '#00B2D5',
      // fillOpacity: polygonList[i].polygonOptions.fillOpacity || 0.5,
      // extrusionHeight: polygonList[i].polygonOptions.extrusionHeight || 0,
      // height: polygonList[i].polygonOptions.height || 0,
      // wallColor: polygonList[i].polygonOptions.wallColor || '#00D3FC',
      // roofColor: polygonList[i].polygonOptions.roofColor || '#00D3FC',
      // strokeStyle: polygonList[i].polygonOptions.strokeStyle || 'solid',
      // strokeDasharray: polygonList[i].polygonOptions.strokeDasharray || [],
      // zIndex: polygonList[i].polygonOptions.zIndex || 10,
      // bubble: polygonList[i].polygonOptions.bubble || false
      for (var i = 0; i < polygonList.length; i++) {
        var polygonOptions = polygonList[i].options?polygonList[i].options:{}
        polygonOptions.strokeColor = polygonOptions.lineColor || '#00B2D5'
        polygonOptions.strokeWeight = polygonOptions.lineWidth || 2
        polygonOptions.strokeOpacity = polygonOptions.lineOpacity || 1
        polygonOptions.strokeStyle = polygonOptions.lineStyle || 'solid'
        polygonOptions.fillColor = polygonOptions.color || '#00B2D5'
        polygonOptions.fillOpacity = polygonOptions.opacity || 0.5
        polygonOptions.zIndex = polygonOptions.zIndex || 10
        var polygon = new AMap.Polygon({
          path: polygonList[i].path,
          extData: {
            showInfoWindow: polygonOptions.showInfoWindow,
            customInfoWindow: polygonOptions.customInfoWindow,
            ...polygonList[i].properties
          },
          ...polygonOptions
        })
        polygon.on('click', this.onClickPolygon)
        polygons.push(polygon)
      }
      this.polygonLayer = new AMap.OverlayGroup(polygons)
      this.map.add(this.polygonLayer)
    },
    loadSpecialPath (config) {
    },
    loadPath (config) {
      console.log('加载轨迹');
      AMap.plugin('AMap.MoveAnimation', () => {
        const list = config.list?config.list:[]
        const options = config.options?config.options:{}
        this.pathConfig = config
        //  线条样式
        var pathStyle = {
          color: 'red',
          width: 5,
          defaultColor: '#00D3FC',
          speed: 80 // m/s
        }
        if (options.line && options.line.defaultColor) {
          pathStyle.defaultColor = options.line.defaultColor
        }
        if (options.line && options.line.width) {
          pathStyle.width = options.line.width
        }
        if (options.line && options.line.color) {
          pathStyle.color = options.line.color
        }
        if (options.speed) {
          pathStyle.speed = options.speed
        }
        // 图标
        var pointSymbol = {
          icon: require('../assets/marker/car.png'),
          width: 28,
          height: 28
        }
        if (options.point && options.point.icon) {
          pointSymbol.icon = options.point.icon
        }
        if (options.point && options.point.width) {
          pointSymbol.width = options.point.width
        }
        if (options.point && options.point.height) {
          pointSymbol.height = options.point.height
        }
        let pointIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(pointSymbol.width, pointSymbol.height),
          // 图标的取图地址
          image: pointSymbol.icon,
          imageSize: new AMap.Size(pointSymbol.width, pointSymbol.height),
          imageOffset: new AMap.Pixel(0, 0)
        });
        // 起点
        var startSymbol = {
          icon: require('../assets/marker/start.png'),
          width: 28,
          height: 28
        }
        if (options.start && options.start.icon) {
          startSymbol.icon = options.start.icon
        }
        if (options.start && options.start.width) {
          startSymbol.width = options.start.width
        }
        if (options.start && options.start.height) {
          startSymbol.height = options.start.height
        }
        let startIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(startSymbol.width, startSymbol.height),
          // 图标的取图地址
          image: startSymbol.icon,
          imageSize: new AMap.Size(startSymbol.width, startSymbol.height),
          imageOffset: new AMap.Pixel(0, 0)
        });
        // 终点
        var endSymbol = {
          icon: require('../assets/marker/end.png'),
          width: 28,
          height: 28
        }
        if (options.end && options.end.icon) {
          endSymbol.icon = options.end.icon
        }
        if (options.end && options.end.width) {
          endSymbol.width = options.end.width
        }
        if (options.end && options.end.height) {
          endSymbol.height = options.end.height
        }
        let endIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(endSymbol.width, endSymbol.height),
          // 图标的取图地址
          image: endSymbol.icon,
          imageSize: new AMap.Size(endSymbol.width, endSymbol.height),
          imageOffset: new AMap.Pixel(0, 0)
        });
        for (var i = 0; i < list.length; i++) {
          var marker = new AMap.Marker({
              map: this.map,
              position: list[i].path[0],
              icon: pointIcon,
              zIndex: 20,
              extData: {
                __index: i,
                ...list[i].properties
              },
              offset: new AMap.Pixel(-pointSymbol.width/2, -pointSymbol.height/2)
          });
          var startMarker = new AMap.Marker({
              map: this.map,
              position: list[i].path[0],
              icon: startIcon,
              offset: new AMap.Pixel(-startSymbol.width/2, -startSymbol.height)
          });
          var endMarker = new AMap.Marker({
              map: this.map,
              position: list[i].path[list[i].path.length-1],
              icon: endIcon,
              offset: new AMap.Pixel(-endSymbol.width/2, -endSymbol.height)
          });
          var polyline = new AMap.Polyline({
            map: this.map,
            path: list[i].path,
            showDir:true,
            strokeColor: pathStyle.defaultColor,  //线颜色
            strokeOpacity: 1,     //线透明度
            strokeWeight: pathStyle.width,      //线宽
            strokeStyle: "solid"  //线样式
          });
          console.log('距离', polyline.getLength());
          var passedPolyline = new AMap.Polyline({
              map: this.map,
              showDir:true,
              strokeColor: pathStyle.color,  //线颜色
              strokeOpacity: 1,
              strokeWeight: pathStyle.width,      //线宽
          });
          this.pointsList.push(marker)
          this.passedList.push(passedPolyline)
          this.pathList.push(polyline)
          marker.on('click', this.onClickPoint);
          marker.on('moving', this.movingAnimation)
          let time = this.getItemTime(polyline, pathStyle.speed)
          marker.moveAlong(list[i].path, {
            // 每一段的时长
            duration: time,//可根据实际采集时间间隔设置
            // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
            autoRotation: true,
            circlable: options.loop
          });
        }
        if (!options.autoMove) {
          setTimeout(() => {
            this.pointsList.forEach(ele => {
              ele.pauseMove()
            })
          }, 100)
        }

      })

    },
    getItemTime (polyline, speed) {
      let count = polyline.getPath().length
      let distance = polyline.getLength()
      let totalTime = distance/speed
      return totalTime / count * 1000
    },
    onClickPoint (e) {
      // e.target.resumeMove();
      let index = e.target.getExtData().__index
      let options = this.pathConfig.options?this.pathConfig.options:{}
      let time = this.getItemTime(this.pathList[index], options.speed || 80)
      e.target.moveAlong(this.pathList[index].getPath(), {
        // 每一段的时长
        duration: time,//可根据实际采集时间间隔设置
        // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
        autoRotation: true,
        circlable: options.loop
      });
    },
    movingAnimation (e) {
      let index = e.target.getExtData().__index
      this.passedList[index].setPath(e.passedPath)
      // passedPolyline.setPath(e.passedPath);
    },
    loadPathOld (config) {

      AMapUI.load(['ui/misc/PathSimplifier', 'ui/overlay/SimpleMarker'], (PathSimplifier, SimpleMarker) => {
        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
        }
        var arr = config.list?config.list:[{
            name: '路线1',
            path: PathSimplifier.getGeodesicPath([116.405289, 39.904987], [87.61792, 43.793308], 100)
        },{
            name: '路线2',
            path: PathSimplifier.getGeodesicPath([112.230863,37.485232], [108.891019,34.208985], 100)
        }, {
            name: '路线3',
            path: PathSimplifier.getGeodesicPath([118.866605,32.075034], [104.10098,30.346236], 100)
        }, {
            name: '路线4',
            path: PathSimplifier.getGeodesicPath([101.596097,36.608384], [109.63809,37.135709], 100)
        }]
        let options = config.options?config.options:{}
        //  线条样式
        var pathStyle = {
          color: 'red',
          width: 5,
          defaultColor: '#00D3FC',
          speed: 80 // m/s
        }
        if (options.line && options.line.defaultColor) {
          pathStyle.defaultColor = options.line.defaultColor
        }
        if (options.line && options.line.width) {
          pathStyle.width = options.line.width
        }
        if (options.line && options.line.color) {
          pathStyle.color = options.line.color
        }
        if (options.speed) {
          pathStyle.speed = options.speed
        }
        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            autoSetFitView:false,
            map: this.map, //所属的地图实例
            data: arr,
            // pathClick: false,
            // clickToSelectPath: false,
            getPath: (pathData, pathIndex) => {
              let startPosition = pathData.path[0]
              let endPosition = pathData.path[pathData.path.length-1]
              // 起点
              var startSymbol = {
                icon: require('../assets/marker/start.png'),
                width: 28,
                height: 28
              }
              if (options.start && options.start.icon) {
                startSymbol.icon = options.start.icon
              }
              if (options.start && options.start.width) {
                startSymbol.width = options.start.width
              }
              if (options.start && options.start.height) {
                startSymbol.height = options.start.height
              }
              let startIcon = new AMap.Icon({
                // 图标尺寸
                size: new AMap.Size(startSymbol.width, startSymbol.height),
                // 图标的取图地址
                image: startSymbol.icon,
                imageSize: new AMap.Size(startSymbol.width, startSymbol.height)
              });
              let startMarker = new AMap.Marker({
                position: startPosition,
                icon: startIcon,
                map: this.map,
                offset: new AMap.Pixel(-startSymbol.width/2, -startSymbol.height)
              });

              startMarker.on('click', (e) => {
                this.navgList[pathIndex].start()
              })
              // 终点
              var endSymbol = {
                icon: require('../assets/marker/end.png'),
                width: 28,
                height: 28
              }
              if (options.end && options.end.icon) {
                endSymbol.icon = options.end.icon
              }
              if (options.end && options.end.width) {
                endSymbol.width = options.end.width
              }
              if (options.end && options.end.height) {
                endSymbol.height = options.end.height
              }
              let endIcon = new AMap.Icon({
                // 图标尺寸
                size: new AMap.Size(endSymbol.width, endSymbol.height),
                // 图标的取图地址
                image: endSymbol.icon,
                imageSize: new AMap.Size(endSymbol.width, endSymbol.height)
              });
              let endMarker = new AMap.Marker({
                position: endPosition,
                icon: endIcon,
                map: this.map,
                offset: new AMap.Pixel(-endSymbol.width/2, -endSymbol.height)
              });

              return pathData.path;
            },
            getHoverTitle: (pathData, pathIndex, pointIndex) => {
              console.log(pathData);
              if (pointIndex === 0) {
                return pathData.properties.name+'：起点'
              } else if (pointIndex === pathData.path.length - 1) {
                return pathData.properties.name+'：终点'
              } else {
                return pathData.properties.name;
              }
            },
            renderOptions: config.options1?config.options:{
              renderAllPointsIfNumberBelow: -1,
              pathTolerance: 2,
              eventSupportInvisible: false,
              eventSupport: false,
              keyPointTolerance: 0,
              pathLineStyle: {
                  // lineWidth: 3,
                  // strokeStyle: '#F7B538',
                  // borderWidth: 1,
                  // borderStyle: '#eeeeee',
                  // dirArrowStyle: false,
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
              },
              pathLineHoverStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: false
              },
              pathLineSelectedStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.defaultColor,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
              },
              dirArrowStyle: {
                  stepSpace: 20,
                  strokeStyle: '#ffffff',
                  lineWidth: 2
              },
              startPointStyle: {
                  radius: 0,
                  fillStyle: '#109618',
                  lineWidth: 1,
                  strokeStyle: '#eeeeee'
              },
              endPointStyle: {
                  radius: 0,
                  fillStyle: '#dc3912',
                  lineWidth: 1,
                  strokeStyle: '#eeeeee'
              },
              keyPointStyle: {
                  radius: 0,
              },
              keyPointHoverStyle: {
                  radius: 0,
              },
              keyPointOnSelectedPathLineStyle: {
                  radius: 0,
              }
            }
        });

        //对第一条线路（即索引 0）创建一个巡航器
        var pointSymbol = {
          icon: require('../assets/marker/car.png'),
          width: 28,
          height: 28
        }
        if (options.point && options.point.icon) {
          pointSymbol.icon = options.point.icon
        }
        if (options.point && options.point.width) {
          pointSymbol.width = options.point.width
        }
        if (options.point && options.point.height) {
          pointSymbol.height = options.point.height
        }
        for (var i = 0; i < arr.length; i++) {
          var navg = pathSimplifierIns.createPathNavigator(i, {
              loop: false, //循环播放
              speed: pathStyle.speed * 3.6,//巡航速度，单位千米/小时
              pathNavigatorStyle: {
                width: pointSymbol.width,
                height: pointSymbol.height,
                pathLinePassedStyle: {
                  lineWidth: pathStyle.width,
                  strokeStyle: pathStyle.color,
                  borderWidth: 1,
                  borderStyle: '#cccccc',
                  dirArrowStyle: true
                },
                //使用图片
                content: PathSimplifier.Render.Canvas.getImageContent(pointSymbol.icon, function onload(){
                  pathSimplifierIns.renderLater();
                }, function onerror(e) {
                  console.log('图片加载失败：', e);
                }),
              },

          });
          this.navgList.push(navg)

        }
      });

    },
    onCloseInfoWindow () {
      this.infoWindow.close();
      this.currentInfo = {}
    },
    onClickMarker (e) {
      this.currentInfo = e.target.getExtData()
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-gaode-infoWindow'])
        }
        this.infoWindow.open(this.map, e.target.getPosition());

      }
      this.$emit('on-click-marker', e.target, this.currentInfo, this.infoWindow)

    },
    onClickPolygon (e) {
      this.currentInfo = e.target.getExtData()
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-gaode-infoWindow'])
        }
        this.infoWindow.open(this.map, [e.lnglat.lng, e.lnglat.lat]);
      }
      this.$emit('on-click-polygon', e.target, this.currentInfo, this.infoWindow)
    },
    onClickMap (e) {
      this.$emit('on-click-map', e)
    }
  },

}
</script>

<style scoped>
  .wh-gaode-wraper {
    width: 100%;
    height: 100%;
  }
  .wh-gaode {
    width: 100%;
    height: 100%;
  }
  .wh-gaode-infoWindow {
    width: 300px;
    background: rgba(39,40,34, 0.8);
    left: -1000px;
    box-sizing: border-box;
    border-radius: 5px;
    overflow: hidden;
  }
  .wh-gaode-infoWindow-title {
    padding: 10px 16px;
    box-sizing: border-box;
    background: rgba(27,29,25, 0.8);
    color: #dbdbdb;
    font-weight: 500;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  .wh-gaode-infoWindow-title>p {
    flex-shrink: 0;
    font-size: 16px;
    margin: 0;
  }
  .wh-gaode-infoWindow-title>img {
    flex-shrink: 1;
    width: 20px;
    display: block;
    cursor: pointer;
  }
  .wh-gaode-infoWindow-content {
    padding: 10px 16px;
    box-sizing: border-box;
    color: #dbdbdb;
    text-align: left;
    font-weight: 400;
  }
  .wh-gaode-infoWindow-bottom {
    position: absolute;
    left: 50%;
    bottom: -40px;
    margin-left: -20px;
    width: 0;
    height: 0;
    border-top: 20px solid rgba(39,40,34, 0.8);
    border-right: 20px solid transparent;
    border-left: 20px solid transparent;
    border-bottom: 20px solid transparent;
  }
  >>> .amap-logo {
    display: none !important;
  }
  >>> .amap-copyright {
    display: none !important;
  }
</style>
